import React from 'react';
import { Col, Modal, Row, Tooltip, Space, Tag, message, Form } from "antd";
import { QuestionCircleFilled, ExclamationCircleOutlined } from '@ant-design/icons';
import TheTable from "@/components/TheTable"
import TheButton from '@/components/TheButton';
import DistributionServe from './distributionServe';
import TheImage from '@/components/TheImage'

import { callPetArchives, allocationSingle, clearAllocation, callCloseServicerOrder } from '@/request/callOrder/orderList.js'
import ServeTableModal from '../components/serveTableModal'
export default class OrderTable extends React.Component {
  constructor(props) {
    super(props)
    this.formRefs = React.createRef()

    this.state = {
      mhcServiceMark: {},//评论弹窗信息
      petInfo: {},//宠物信息
      orderInfo: props.orderInfo, //数据信息
      dataSource: [],
      columns: [
        {
          title: '服务',
          dataIndex: "service",
          key: "service",
          render: (_, record) => {
            let serviceType = ''
            let skuInfoValue = [] //规格信息数据值 规格值可能会存在多个 多个情况下、分隔显示
            if (record.skuInfoObj) {
              if (record.skuInfoObj.specValues) {
                skuInfoValue = record.skuInfoObj.specValues.map(v => {
                  return v.specsValue
                }).join('/')
              }
              if (record.skuInfoObj.serviceType) {
                // 服务类型
                switch (record.skuInfoObj.serviceType) {
                  case 'FEED':
                    serviceType = '喂养'
                    break
                  case 'CARE':
                    serviceType = '洗护'
                    break
                  default:
                    serviceType = '-'
                }
              }
            }
            return (
              <div style={{ width: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                <Tooltip title={
                  <div>
                    <span>{serviceType}</span>
                    <span style={{ margin: '0 5px' }}>|</span>
                    <span>{skuInfoValue}</span>
                  </div>
                } >
                  <span>{serviceType}</span>
                  <span style={{ margin: '0 5px' }}>|</span>
                  <span>{skuInfoValue}</span>
                </Tooltip>

              </div >
            )
          }
        },
        {
          title: '服务时间',
          dataIndex: "orderCode",
          key: "orderCode",
          render: (_, record) => {
            return <Space>
              <span>{record.serviceDate}&nbsp;{record.serviceWeek}&nbsp;{record.serviceStartTime}~{record.serviceFinishTime}</span>
              {record.orderDetailType === 1 && <Tag color="error">变更</Tag>}
            </Space>
          }
        },
        {
          title: '金额（元）',
          dataIndex: "orderAmount",
          key: "orderAmount ",
          render: (text, record) => {
            return <Space>
              {text % 100 === 0 ? '￥' + React.$transNum(text, 0, -2) : <React.$Price price={text || 0} />}
              <Tooltip title={
                <Space direction='vertical' style={{ fontSize: 12 }}>
                  <Row >
                    <Col>基础金额:</Col>
                    <Col>{record.baseAmount % 100 === 0 ? '￥' + React.$transNum(record.baseAmount, 0, -2) : <React.$Price price={record.baseAmount || 0} />}</Col>
                  </Row>
                  <Row  >
                    <Col>距离加价:</Col>
                    <Col>{record.distanceExtraAmount % 100 === 0 ? '￥' + React.$transNum(record.distanceExtraAmount, 0, -2) : <React.$Price price={record.distanceExtraAmount || 0} />}</Col>
                  </Row>
                  <Row >
                    <Col>节假日加价:</Col>
                    <Col>{record.holidayExtraAmount % 100 === 0 ? '￥' + React.$transNum(record.holidayExtraAmount, 0, -2) : <React.$Price price={record.holidayExtraAmount || 0} />}</Col>
                  </Row>
                  <Row  >
                    <Col>多宠加价:</Col>
                    <Col>{record.petExtraAmount % 100 === 0 ? '￥' + React.$transNum(record.petExtraAmount, 0, -2) : <React.$Price price={record.petExtraAmount || 0} />}</Col>
                  </Row>
                </Space>
              }>
                <QuestionCircleFilled />
              </Tooltip>
            </Space>
          }
        },
        {
          title: '实付金额（元）',
          dataIndex: "payAmount",
          key: "payAmount",
          render: (text) => {
            return text % 100 === 0 ? '￥' + React.$transNum(text, 0, -2) : <React.$Price price={text || 0} />
          }
        },
        {
          title: '分配状态',
          dataIndex: "allocationStatus",
          key: "allocationStatus",
          render: (text, record) => {
            let allocationStatus = ''
            switch (text) {
              case 'ASSIGNED':
                allocationStatus = '已分配'
                break
              case 'NON_ASSIGNED':
                allocationStatus = '待分配'
                break
              default:
                allocationStatus = '-'
            }
            // 已分配状态  则弹出已分配的服务者信息弹窗
            return record.allocationStatus === 'ASSIGNED' ? <TheButton onClick={() => { this.setState({ isServeListModal: true, orderDetailId: record.orderDetailId }) }}>已分配</TheButton> : allocationStatus
          }
        },
        {
          title: '服务者',
          dataIndex: "servicerName",
          key: "servicerName",
          render: (text, record) => {
            return record.servicerName ? <TheButton onClick={() => { this.props.history.push('/call/servicer/servicerList/detail/' + record.servicerId + '/' + 'view') }}>{record.servicerName}</TheButton> : '-'
          }
        },
        {
          title: '宠物',
          dataIndex: "petInfo",
          key: "petInfo",
          render: (text, record) => {
            let petInfo = record.petInfoObj
            // 展示名称 超过4个字符展示... 否则正常展示全部， 以、分隔
            let petNameText = petInfo.map(item => {
              item = item.petName.substring(0, 4) + (item.petName.length > 4 ? '...' : '')
              return item
            }).join('、')
            // tooltipPetName 展示全部名称
            let tooltipPetName = petInfo.map(item => {
              return item.petName
            }).join('、')
            return <>
              {
                petInfo.map(item => {
                  return <TheButton onClick={() => { this.petInfoShow(item.petArchivesId) }}>{item.petName}</TheButton>
                })
              }
            </>

            // <Tooltip title={tooltipPetName}>
            //   <span>{petNameText}</span>
            // </Tooltip>
          }
        },
        {
          title: '退款/变更',
          dataIndex: "orderCode",
          key: "orderCode",
          render: (_, record) => {
            return record.salesReturnDetailList && record.salesReturnDetailList.length > 0 ? record.salesReturnDetailList.map(item => {
              let btn = '', refundStatus = '', changeStatus = '', path = ''
              //refundStatus 退款枚举值  
              switch (item.refundStatus) {
                case '1':
                  refundStatus = '待处理'
                  break
                case '2':
                  refundStatus = '退款成功'
                  break
                case '3':
                  refundStatus = '退款失败'
                  break
                case '0':
                  refundStatus = '退款关闭'
                  break
                default:
                  refundStatus = '-'
              }
              //changeStatus 售后枚举值
              switch (item.changeStatus) {
                case '1':
                  changeStatus = '待处理'
                  break
                case '2':
                  changeStatus = '变更成功'
                  break
                case '0':
                  changeStatus = '变更关闭'
                  break
                default:
                  changeStatus = '-'
              }
              switch (item.refundDetailType) {
                case '0':
                  btn = changeStatus
                  path = `/call/order/afterSaleOrder/changeDetails/${item.salesReturnId}` //变更地址
                  break
                case '1':
                  btn = changeStatus
                  path = `/call/order/afterSaleOrder/changeDetails/${item.salesReturnId}` //变更地址
                  break
                case '2':
                  btn = refundStatus
                  path = `/call/order/afterSaleOrder/refundDetails/${item.salesReturnId}` //退款地址
                  break
              }
              return <TheButton onClick={() => { this.props.history.push(path) }}>{btn}</TheButton>
            }) : '-'
          }
        },
        {
          title: '状态',
          dataIndex: "orderStatus",
          key: "orderStatus",
          render: (text) => {
            let orderStatus = ''
            switch (text) {
              case 'WAIT_PAY':
                orderStatus = '待付款'
                break
              case 'WAIT_ORDER_TAKING':
                orderStatus = '待接单'
                break
              case 'WAIT_SERVICE':
                orderStatus = '待服务'
                break
              case 'IN_PROCESS':
                orderStatus = '服务中'
                break
              case 'FINISH':
                orderStatus = '已完成'
                break
              case 'CLOSE':
                orderStatus = '已关闭'
                break
              default:
                orderStatus = '-'
            }
            return orderStatus
          }
        },
        {
          title: '评价',
          render: (text, record) => {
            return <>
              <TheButton haspermi={['call:orderListDetails:allocation']}
                onClick={() => record.mhcServiceMark ? this.evaluateShow(record.mhcServiceMark) : ''}>  {record.mhcServiceMark ? { PMY: "满意", PYB: "一般", PBM: "不满意" }[record.mhcServiceMark.markType] : '-'}</TheButton>
            </>
          }
        },
        {
          title: '操作',
          render: (text, record) => {
            return <>
              {
                record.orderStatus === 'WAIT_ORDER_TAKING' ? <TheButton haspermi={['call:orderListDetails:allocation']} onClick={() => { this.distributionModal(record, 'single', this.state.orderInfo) }}>分配</TheButton> : <TheButton >-</TheButton>
              }
              {record.canNewAllocation && <TheButton className='anewDistribution' onClick={() => this.anewDistribution(record, 'single', this.state.orderInfo)}>重新分配</TheButton>}
            </>
          }
        }
      ],
      isAllocationModal: false,//分配信息弹窗
      allocationTotal: 0,
      isDurationModal: false,//分配服务者弹窗
      evaluateVisibility: false,//评价弹窗
      petVisibility: false,//宠物信息弹窗
      selectServeId: [],//
      allocationType: null,//分配方式 整单分配whole 单行分配single
      userOrderId: undefined,// 整单订单id
      userOrderDetailId: undefined,//订单行id
      version: null, //订单版本号
      submitAllotBtnLoading: false,//确认分配按钮loading
    }
  }
  async componentDidMount() {
    await this.getData()
  }
  // 数据处理
  getData = async () => {
    let { orderInfo } = this.props
    this.setState({ dataSource: [] })
    if (orderInfo) {
      this.setState({ dataSource: orderInfo.orderDetailList })
    }
  }
  anewDistribution = (value, allocationType, orderInfo) => {
    React.$confirm({
      title: "提示",
      okText: "继续",
      type: 'warning',
      content: "当前订单已有服务者接单，请确认该服务者是否无法继续服务，需要变更服务者接单？",
      onOk: async () => {
        let res = await callCloseServicerOrder({ id: value.orderDetailId })
        if (res.code === 0) {
          this.distributionModal(value, allocationType, orderInfo)
        }
      },
      onCancel: async () => {

      }
    });
  }
  evaluateShow = (mhcServiceMark) => {
    this.setState({ evaluateVisibility: true, mhcServiceMark })
  }
  petInfoShow = async (petArchivesId) => {
    let res = await callPetArchives({ petArchivesId })
    if (res.code === 0) {
      this.setState({ petVisibility: true, petInfo: res.data })
    }
  }

  //已分配弹窗
  allocationModal = async (value) => {
    if (value) {
      this.setState({ isAllocationModal: true, allocationType: value.allocationType, orderId: value.orderId, orderDetailId: value.orderDetailId })
    }
  }
  //分配服务者弹窗
  distributionModal = (value, allocationType, orderInfo) => {
    if (value) {
      this.setState({ isDurationModal: true, allocationType, orderId: value.orderId, version: orderInfo.version, orderDetailId: value.orderDetailId })
    }
  }
  // 勾选的服务者id集合
  selectServe = (selectServicerIds) => {
    this.setState({ selectServicerIds })
  }
  // 确认分配服务者并关闭对应的弹窗
  submitDistribution = async () => {
    let { selectServicerIds, orderId, orderDetailId, allocationType, version } = this.state
    this.setState({ submitAllotBtnLoading: true })
    if (allocationType === 'single') {
      let res = await allocationSingle({ servicerIds: selectServicerIds, userOrderId: orderId, userOrderDetailId: orderDetailId, version })
      if (res.code === 0) {
        message.success('分配成功！')
        this.setState({ isDurationModal: false, selectServicerIds: [] }, () => {
          this.props.getRequest(orderId)
        })
        // window.location.reload() //分配成功后刷新下页面
      }
      if (res.code === 20008) {
        Modal.confirm({
          title: '提醒',
          icon: <ExclamationCircleOutlined />,
          content: '当前订单已进行过整单分配，需取消原先的整单分配方可进行的单行分配，是否取消原先的整单分配，继续单行分配',
          okText: '继续',
          cancelText: '取消',
          onOk: async () => {
            let res = await clearAllocation({ userOrderId: orderId, version })
            if (res.code === 0) {
              let res = await allocationSingle({ servicerIds: selectServicerIds, userOrderId: orderId, userOrderDetailId: orderDetailId, version })
              if (res.code === 0) {
                message.success('分配成功！')
                this.setState({ isDurationModal: false, selectServicerIds: [] }, () => {
                  this.props.getRequest(orderId)
                })
                // window.location.reload() //分配成功后刷新下页面
              }
            }
          }
        })
      }
    }
    this.setState({ submitAllotBtnLoading: false })
  }
  // 跳转至售后详情页
  afterSaleDetails = (path) => {
    if (path && path !== '') {
      this.props.history.push(path)
    }
  } //分配信息弹窗
  getServerListModal = async (value) => {
    this.setState({ isServeListModal: value })
  }
  render() {
    const { petInfo, petVisibility, mhcServiceMark, evaluateVisibility, dataSource, columns, isServeListModal, orderInfo, isDurationModal, submitAllotBtnLoading, allocationType, orderId, orderDetailId } = this.state
    return (
      <div >
        <TheTable dataSource={dataSource} columns={columns} />
        <Row style={{ display: 'flex', justifyContent: 'flex-end', marginRight: 20, alignItems: 'center' }}>
          <Col >
            <Row style={{ margin: '10px 0' }}>
              <Col>服务总价:</Col>
              <Col style={{ marginLeft: 10 }}>
                {orderInfo.orderAmount % 100 === 0 ? '￥' + React.$transNum(orderInfo.orderAmount, 0, -2) : <React.$Price price={orderInfo.orderAmount} />}
              </Col>
            </Row>
            <Row style={{ margin: '10px 0' }}>
              <Col>实付金额: </Col>
              <Col style={{ color: 'red', marginLeft: 10 }}>
                {orderInfo.payAmount % 100 === 0 ? '￥' + React.$transNum(orderInfo.payAmount, 0, -2) : <React.$Price price={orderInfo.payAmount} />}
              </Col>
            </Row>
          </Col>
        </Row>
        {
          isServeListModal && <ServeTableModal isModalOpen={isServeListModal} orderDetailId={orderDetailId} getServerListModal={this.getServerListModal}></ServeTableModal>
        }
        <Modal
          width={'30%'}
          title="宠物详情"
          open={petVisibility}
          onCancel={() => { this.setState({ petVisibility: false }) }}
          footer={[]}
          destroyOnClose>
          <Row style={{ height: '40px' }}>
            <Col span={12}>宠物分类：{["狗", "猫", "异宠"][petInfo.petSpecies]}</Col>
            <Col span={12}>出生日期：{petInfo.birthday}</Col>
          </Row>
          <Row style={{ height: '50px' }}>
            <Col span={12}>
              <div style={{ display: 'flex' }}>
                <div>宠物头像：</div> <TheImage src={petInfo.petCardShowImages} width={50} height={50} />
              </div>
            </Col>
            <Col span={12}>体重：{petInfo.weight + 'kg'}</Col>
          </Row>
          <Row style={{ height: '40px' }}>
            <Col span={12}>宠物姓名：{petInfo.petName}</Col>
            <Col span={12}>性别：{["", "公", "母"][petInfo.petSex]}</Col>
          </Row>
          <Row style={{ height: '40px' }}>
            <Col span={12}>品种：{petInfo.petVarieties}</Col>
            <Col span={12}>绝育情况：{{ Y: "已绝育", N: "未绝育" }[petInfo.sterilizationStatus]}</Col>
          </Row>
          <Row style={{ height: '40px' }}>
            <Col span={12}></Col>
            <Col span={12}>疫苗情况：{{ Y: "已接种", N: "未接种" }[petInfo.vaccineStatus]}</Col>
          </Row>
        </Modal>
        <Modal
          width={'30%'}
          title="评价详情"
          open={evaluateVisibility}
          onCancel={() => { this.setState({ evaluateVisibility: false }) }}
          footer={[]}
          destroyOnClose>
          <Form labelWrap={true}>
            <Form.Item
              label="整体评价"
              name="username"
            >
              {{ PMY: "满意", PYB: "一般", PBM: "不满意" }[mhcServiceMark.markType]}
            </Form.Item>
            <Form.Item
              label="评价标签"
              name="username"
            >
              {mhcServiceMark.markLabel}
            </Form.Item>
            <Form.Item
              label="评价描述"
              name="username"
            >
              {mhcServiceMark.markContent}
            </Form.Item>
            <Form.Item
              label="凭证"
              name="username"
            >
              <Row>
                {
                  mhcServiceMark.imageUrl && mhcServiceMark.imageUrl.split(',').map(item => {
                    return <Col span={6}>
                      <TheImage src={item} width={80} height={80} />
                    </Col>
                  })
                }
              </Row>
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          width={'70%'}
          title="分配服务者"
          open={isDurationModal}
          okText='确认分配'
          confirmLoading={submitAllotBtnLoading}
          onOk={this.submitDistribution}
          destroyOnClose
          onCancel={() => { this.setState({ isDurationModal: false, selectServeId: [] }) }}>
          <DistributionServe orderId={orderId} orderDetailId={orderDetailId} allocationType={allocationType} getSelectKeys={this.selectServe} ></DistributionServe>
        </Modal>
      </div>
    )
  }
}